package SSDbackend

import chisel3._
import chisel3.util._
import nutcore.NutCoreModule


class SSDRF extends NutCoreModule {
  val io = IO(new RfIO)

  val rf = Mem(32, UInt(64.W))
  //读写冲突
  val rwhit = Vec(4, UInt(2.W))
  val rwhitData = Vec(4, UInt(64.W))
  val rwhitTag = Vec(4, Bool())
  for (i <- 0 to 3) rwhitTag(i) := rwhit(i).orR

  for (i <- 0 to 3) {
    rwhit(i) := {
      (io.raddr(i) == io.waddr(0), io.raddr(i) == io.waddr(1)) match {
        case (false, false) => "b00".U
        case (false, true) => "b01".U
        case (true, false) => "b10".U
        case (true, true) => "b11".U
      }
    }
  }
  val rwhitTable = Array(BitPat("b00".U) -> 0.U(64.W), BitPat("b01".U) -> io.wdata(1), BitPat("b10".U) -> io.wdata(0), BitPat("b11".U) -> io.wdata(1))

  for (i <- 0 to 3) rwhitData(i) := Lookup(rwhit(i), 0.U(64.W), rwhitTable)
  // read
  for(i <- 0 to 3) io.rdata(i) := Mux(rwhitTag(i),rwhitData,rf.read(io.raddr(i)))

  //写冲突
  val wwhit = Bool()
  wwhit := io.waddr(0) === io.waddr(1) && io.wen(0) && io.wen(1)
  //write
  rf.write(io.waddr(0),io.wen(0))
  rf.write(io.waddr(1),io.wen(1) && !wwhit)
}
